package com.hanxiaozhang.tree.binarytreerecursion;

import com.hanxiaozhang.tree.BinaryTreeUtil;
import com.hanxiaozhang.tree.Node;

/**
 * 〈一句话功能简述〉<br>
 * 〈给定一棵二叉树的头节点head，返回这颗二叉树是不是满二叉树〉
 *  这里说的是完美二叉树
 *
 *
 * @author hanxinghua
 * @create 2021/10/28
 * @since 1.0.0
 */
public class IsFull {

    public static void main(String[] args) {
        int maxLevel = 5;
        int maxValue = 100;
        int testTimes = 1000000;
        for (int i = 0; i < testTimes; i++) {
            Node head = generateRandomBST(maxLevel, maxValue);
            if (isFull1(head) != isFull2(head)) {
                System.out.println("Oops!");
            }
        }
        System.out.println("finish!");
    }

    public static boolean isFull1(Node head) {
        if (head == null) {
            return true;
        }
        int height = h(head);
        int nodes = n(head);
        // 2^k-1
        return (1 << height) - 1 == nodes;
    }

    public static int h(Node head) {
        if (head == null) {
            return 0;
        }
        return Math.max(h(head.left), h(head.right)) + 1;
    }

    public static int n(Node head) {
        if (head == null) {
            return 0;
        }
        return n(head.left) + n(head.right) + 1;
    }

    /**
     * 是否充满
     *
     * @param head
     * @return
     */
    public static boolean isFull2(Node head) {
        if (head == null) {
            return true;
        }
        Info all = process(head);
        return (1 << all.height) - 1 == all.nodes;
    }

    /**
     * 递归
     *
     * @param head
     * @return
     */
    public static Info process(Node head) {
        if (head == null) {
            return new Info(0, 0);
        }
        Info leftInfo = process(head.left);
        Info rightInfo = process(head.right);
        // 高度
        int height = Math.max(leftInfo.height, rightInfo.height) + 1;
        // 节点个数
        int nodes = leftInfo.nodes + rightInfo.nodes + 1;
        return new Info(height, nodes);
    }

    /**
     * 实体 记录高度和节点个数
     */
    public static class Info {
        /**
         * 高度
         */
        public int height;
        /**
         * 个数
         */
        public int nodes;

        public Info(int h, int n) {
            height = h;
            nodes = n;
        }
    }

    // for test
    public static Node generateRandomBST(int maxLevel, int maxValue) {
        return BinaryTreeUtil.generate(1, maxLevel, maxValue);
    }


}
